package com.todo.event.activity.application.handler.dynamicwords;

import com.alibaba.fastjson.JSONObject;
import com.todo.event.activity.common.enums.EventActivityDynamicWordEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author azhebuxing
 * @date 2025/1/13 17:51
 * @description
 */
@Slf4j
@Component
public class DynamicWordsFactory {

    @Autowired
    private List<AbstractDynamicWordsHandle> dynamicWordsHandlers;

    ThreadPoolExecutor dynamicExecute = new ThreadPoolExecutor(10, 10, 5000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(100));


    public Map<EventActivityDynamicWordEnum, Object> handle(List<EventActivityDynamicWordEnum> dynamicWords) {
        List<CompletableFuture> futureList = new ArrayList<>();
        for (AbstractDynamicWordsHandle dynamicWordsHandle : dynamicWordsHandlers) {
            CompletableFuture future = CompletableFuture.supplyAsync(() -> dynamicWordsHandle.handle(dynamicWords), dynamicExecute);
            futureList.add(future);
        }
        Map<EventActivityDynamicWordEnum, Object> result = new HashMap<>();
        try {
            CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).get(5000, TimeUnit.MILLISECONDS);
            futureList.forEach(future -> {
                try {
                    Map<EventActivityDynamicWordEnum, Object> map = (Map<EventActivityDynamicWordEnum, Object>) future.get();
                    if (Objects.nonNull(map)) {
                        result.putAll(map);
                    }
                } catch (Exception ignore) {
                }
            });
        } catch (Exception ex) {
            log.error("DynamicWordsFactory#handle 批处理动态词系统异常 ，dynamicWords：【{}】", JSONObject.toJSONString(dynamicWords), ex);
        }
        return result;
    }
}
